There is a very good post about Associative Arrays considered harmful by Andrew Dupont.
The title is a bit misleading but correct. When coming accross a piece of JavaScript like this
foo["test"] = 1;
there is nothing wrong about it. It’s the basic usage scheme of assoziative arrays. Or should i rather say objects?
While in languages such as PHP arrays used like this $foo = array("test" => 1);
is perfectly correct.
In JavaScript
var foo = new Array();
foo["test"] = 1;
works but does not do what you want.
I don’t need to repeat Andrew’s really great post, but basically you should use Object
instead of Array
.
var foo = new Object(); // same as var foo = {};
foo["test"] = 1; // same as foo.test = 1;
Now go and read Andrew’s post.
via Erik Arvidsson.
btw: that post lead me to Object.prototype is verboten which explains for me why my for (i in myvar) {}
loops never worked correctly. I was using prototype.js version < 1.4 (which messed with Object.prototype).
Using ‘Object’ as an associative array can be bad too:
http://www.bluishcoder.co.nz/2006/05/associative-arrays-and-javascript.html
Basically naieve use of Object can return built in operations on Object (like toString).
Object.prototype is erlaubt ;-)
http://www.thomasfrank.se/object_prototype_is_erlaubt.html